/**
 * Created by YY on 16/8/17.
 */
var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

exports.queryAllCompletePlan = function (completeFun) {
    var entity = entityCollection.getEntity("CompletePlan");
    entity.find({}, null, [{
        path: "ItemMaster",
        select: "Code Name"
    }], function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询完工计划表失败！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

exports.findCompletePlan = function (id, completeFun) {
    var entity = entityCollection.getEntity("CompletePlan");
    entity.findOne({_id: id}, null,
        function (err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        });
};
//更新
exports.updateByValue = function (id, value, completeFun) {
    var entity = entityCollection.getEntity("CompletePlan");
    entity.updateByValue({_id: id}, value, function (err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '更新完成量错误';
            newErr.message = '更新失败';
            completeFun(newErr);
        } else {
            completeFun(null, result);
        }
    });
};
//通过日期查找完工计划(按时间降序)
exports.getCompletePlanByDate = function (date, completeFun) {
    
    var entity = entityCollection.getEntity("CompletePlan");
    entity.find({CompleteTime:{$gte:date+" 00:00:00",$lte:date+" 23:59:59"}}, {CompleteTime: -1}
        , [{
        path: "ItemMaster",
        select: "Code Name"
    }], function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询完工计划表失败！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

exports.queryCompletePlan = function () {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("CompletePlan");
    entity.Entity
    .find({ Status: 0 }, 'Code LotNumber ItemMaster CompleteTime')
    .sort({ CompleteTime: 1 })
    .populate({
        path: 'ItemMaster',
        select: 'Code Name Specification'
    }).exec(function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询完工计划表失败！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });

    return deferred.promise;
};


